/* URBAN EXPLORER PROJECT
 * 
 * Author: Karthick Nanmaran (s1051713), School of Informatics, The University of Edinburgh
 * Email: karthicknanmaran@gmail.com
 * 
 * Supervisor: Dr.William Mackaness, 
 * 			   Institute of Geography,
 * 			   School of GeoSciences,
 * 			   The University of Edinburgh.
 * Email: william.mackaness@ed.ac.uk
 * 
 * This code can be found online at http://code.google.com/p/urban-explorers/
*/
package Firstdroid.Gps;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class BluetoothActivity extends Activity {
 
 private static final int REQUEST_ENABLE_BT = 1;
 private static final int REQUEST_Turn_On_Discoverable = 3;
 
 ListView listDevicesFound;
 Button btnScanDevice;
 Button btnRSSI;
 Spinner spnDiscoverableDuration;
 Button btnTurnOnDiscoverable;
 TextView stateBluetooth;
 BluetoothAdapter bluetoothAdapter;
 
 ArrayAdapter<String> btArrayAdapter;
 
 String[] optDiscoverableDur = {"10 sec", "60 sec", "120 sec", "240 sec", "300 sec"};
 int[] valueDiscoverableDur = {10, 60, 120, 240, 300};
 
 /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.bluetooth);
        
        btnScanDevice = (Button)findViewById(R.id.scandevice);
        btnRSSI = (Button)findViewById(R.id.RSSI);
        
        spnDiscoverableDuration = (Spinner)findViewById(R.id.discoverableduration);
        btnTurnOnDiscoverable = (Button)findViewById(R.id.turnondiscoverable);
        
        stateBluetooth = (TextView)findViewById(R.id.bluetoothstate);
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        
        listDevicesFound = (ListView)findViewById(R.id.devicesfound);
        btArrayAdapter = new ArrayAdapter<String>(BluetoothActivity.this, android.R.layout.simple_list_item_1);
        listDevicesFound.setAdapter(btArrayAdapter);
        
        CheckBlueToothState();
        
        btnScanDevice.setOnClickListener(btnScanDeviceOnClickListener);
        btnRSSI.setOnClickListener(btnRSSIOnClickListener);

        registerReceiver(ActionFoundReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
        
        btnTurnOnDiscoverable.setOnClickListener(btnTurnOnDiscoverableOnClickListener);
        
        ArrayAdapter<String> adapterDiscoverableDur = new ArrayAdapter<String>(this,
          android.R.layout.simple_list_item_1, optDiscoverableDur);
        adapterDiscoverableDur.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spnDiscoverableDuration.setAdapter(adapterDiscoverableDur);

        registerReceiver(ScanModeChangedReceiver, new IntentFilter(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED));
    }
    
    @Override
 protected void onDestroy() {
  // TODO Auto-generated method stub
  super.onDestroy();
  unregisterReceiver(ScanModeChangedReceiver);
 }

 private void CheckBlueToothState(){
     if (bluetoothAdapter == null){
         stateBluetooth.setText("Bluetooth NOT support");
        }else{
         if (bluetoothAdapter.isEnabled()){
          if(bluetoothAdapter.isDiscovering()){
           stateBluetooth.setText("Bluetooth is currently in device discovery process.");
          }else{
           stateBluetooth.setText("Bluetooth is Enabled.");
           btnTurnOnDiscoverable.setEnabled(true);
          }
         }else{
          stateBluetooth.setText("Bluetooth is NOT Enabled!");
          Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
             startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
         }
        }
    }
    
    private Button.OnClickListener btnTurnOnDiscoverableOnClickListener = new Button.OnClickListener(){

  @Override
  public void onClick(View arg0) {
   // TODO Auto-generated method stub
   Intent discoverableIntent 
    = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
   int dur = valueDiscoverableDur[(int)spnDiscoverableDuration.getSelectedItemId()];
   discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, dur);
   startActivityForResult(discoverableIntent, REQUEST_Turn_On_Discoverable);
  }};

  
  private Button.OnClickListener btnRSSIOnClickListener = new Button.OnClickListener(){

	  @Override
	  public void onClick(View arg0) {
	   // TODO Auto-generated method stub
	   Intent intent = new Intent(BluetoothDevice.ACTION_FOUND);
	   String action = intent.getAction();
	   if(BluetoothDevice.ACTION_FOUND.equals(action)) {
	   short rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI,Short.MIN_VALUE);
	   if (( rssi < -30 ) && ( rssi > -50 ))
	   {  
       Toast.makeText(getApplicationContext(),"  RSSI: " + rssi + " dBm", Toast.LENGTH_SHORT).show();
	   }
	   else if(rssi < -50 )
	   {
	       Toast.makeText(getApplicationContext(),"  RSSI: " + rssi + " dBm" + "\n The person turned Left", Toast.LENGTH_SHORT).show();
	   }
	   else if(rssi > -30 )
	   {
	       Toast.makeText(getApplicationContext(),"  RSSI: " + rssi + " dBm" + "\n The person turned Right", Toast.LENGTH_SHORT).show();
	   }
	   }
	  }}; 

  
 @Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  // TODO Auto-generated method stub
  if(requestCode == REQUEST_ENABLE_BT){
   CheckBlueToothState();
  }if (requestCode == REQUEST_Turn_On_Discoverable){
   if(resultCode == RESULT_OK){

   }else if (resultCode == RESULT_CANCELED){
    Toast.makeText(BluetoothActivity.this, "User Canceled", Toast.LENGTH_LONG).show();
   }
  }
 }

 private Button.OnClickListener btnScanDeviceOnClickListener = new Button.OnClickListener(){

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
btArrayAdapter.clear();
bluetoothAdapter.startDiscovery();
}};

 private final BroadcastReceiver ScanModeChangedReceiver = new BroadcastReceiver(){

  @Override
  public void onReceive(Context context, Intent intent) {
   // TODO Auto-generated method stub
   String action = intent.getAction();
   if(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED.equals(action)) {
    
    int mode = intent.getIntExtra(BluetoothAdapter.EXTRA_SCAN_MODE, BluetoothAdapter.ERROR);
    String strMode = "";
    
    switch(mode){
    case BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE:
     strMode = "mode changed: SCAN_MODE_CONNECTABLE_DISCOVERABLE";
     break;
    case BluetoothAdapter.SCAN_MODE_CONNECTABLE:
     strMode = "mode changed: SCAN_MODE_CONNECTABLE";
     break;
    case BluetoothAdapter.SCAN_MODE_NONE:
     strMode = "mode changed: SCAN_MODE_NONE";
     break;
    }
    
    Toast.makeText(BluetoothActivity.this, strMode, Toast.LENGTH_LONG).show();
         }
  }};
    
  private final BroadcastReceiver ActionFoundReceiver = new BroadcastReceiver(){

	  @Override
	  public void onReceive(Context context, Intent intent) {
	   // TODO Auto-generated method stub
	   String action = intent.getAction();
	   if(BluetoothDevice.ACTION_FOUND.equals(action)) {
	             BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
	             btArrayAdapter.add(device.getName() + "\n" + device.getAddress());
	             btArrayAdapter.notifyDataSetChanged();
	             short rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI,Short.MIN_VALUE);
	           //Toast.makeText(getApplicationContext(),"  RSSI: " + rssi, Toast.LENGTH_SHORT).show();
	             if (( rssi < -30 ) && ( rssi > -50 ))
	             {  
	             Toast.makeText(getApplicationContext(),"  RSSI: " + rssi + " dBm", Toast.LENGTH_SHORT).show();
	      	     }
	      	     else if(rssi < -50 )
	      	     {
	      	       Toast.makeText(getApplicationContext(),"  RSSI: " + rssi + " dBm" + "\n The person turned Left", Toast.LENGTH_SHORT).show();
	      	     }
	      	     else if(rssi > -30 )
	      	     {
	      	       Toast.makeText(getApplicationContext(),"  RSSI: " + rssi + " dBm" + "\n The person turned Right", Toast.LENGTH_SHORT).show();
	      	     }

	         }
	   //else if(BluetoothDevice.EXTRA_RSSI)
	  }};
}